package jvm.metaspace;

import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;

/**
 * @Author: ideaAdmin
 * TODO: Class
 * TODO: 设置元空间的初始大小和最大大小 然后加载类 导致元空间的OOM
 *         -XX:MetaspaceSize=10M -XX:MaxMetaspaceSize=10M
 * Date: 2022/2/22:19:50
 * Description:
 */

public class SetMetaspaceInitSizeOOM extends ClassLoader {
    public static void main(String[] args) {
        int j = 0;
        SetMetaspaceInitSizeOOM setMetaspaceInitSizeOOM = new SetMetaspaceInitSizeOOM();
        try {
            for (int i = 0; i < 10000; i++) {
                //创建 ClassWriter ,用于生成类的二进制字节码
                ClassWriter classWriter = new ClassWriter(0);
                //指明版本号 修饰符 类名 包名  父类 接口
                classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Class" + i,
                        null, "java/lang/Object", null);

                byte[] code = classWriter.toByteArray();
                setMetaspaceInitSizeOOM.defineClass("Class" + i, code, 0, code.length);
                j++;
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(j);
        }

    }
}
